<template>
  <div class="p-2">
    <div ref="chartRef" style="width: 100%; height: 600px"></div>
  </div>
</template>

<script setup lang="ts">
import { defineProps, onMounted, ref } from 'vue';
import * as echarts from 'echarts';
import { listSymbols, listMarket } from '@/api/market/market';  // 替换原来的axios导入

// 添加props定义
const props = defineProps({
  symbol: {
    type: String,
    required: true
  }
});
const chartRef = ref<HTMLElement | null>(null);
const symbols = ref<string[]>([]); // 存储所有股票代码

// K线图的上涨和下跌颜色
const upColor = '#ec0000';
const upBorderColor = '#8A0000';
const downColor = '#00da3c';
const downBorderColor = '#008F28';

const chartData = ref({
  categoryData: [] as string[],
  values: [] as number[][]
});

// 修改后的 fetchSymbols 函数
const fetchSymbols = async () => {
  try {
    const response = await listSymbols();
    symbols.value = response.data; // 根据实际接口返回结构调整
  } catch (error) {
    console.error('Error fetching symbols:', error);
  }
};

// 添加watch监听symbol变化
watch(
  () => props.symbol,
  (newVal) => {
    fetchData();
  }
);

// 修改后的 fetchData 函数
const fetchData = async () => {
  try {
    const response = await listMarket({
      // symbol: selectedSymbol.value,
      symbol: props.symbol, // 使用props中的symbol
      pageSize: 1000,
      pageNum: 1
    });

    // 处理数据并更新 chartData
    const data = response.rows; // 修改数据访问方式

    // 处理原始数据，转化为ECharts需要的格式
    const rawData = data.map((item: any) => [
      item.time.split(' ')[0], // 修改这里：分割日期部分
      parseFloat(item.open), // 开盘价
      parseFloat(item.preclose), // 收盘价
      parseFloat(item.low), // 最低价
      parseFloat(item.high) // 最高价
    ]);

    const { categoryData, values } = splitData(rawData);

    chartData.value = { categoryData, values };
    renderChart(); // 渲染图表
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

// 分割数据函数
function splitData(rawData: (string | number)[][]) {
  const categoryData: string[] = [];
  const values: number[][] = [];

  rawData.forEach((item) => {
    const date = item[0] as string;
    categoryData.push(date);
    values.push(item.slice(1) as number[]);
  });

  return { categoryData, values };
}

// 渲染图表函数
function renderChart() {
  if (!chartRef.value) {
    return;
  }

  const myChart = echarts.init(chartRef.value);

  const option = {
    title: {
      text: '上证指数',
      left: 0
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30']
    },
    grid: {
      left: '10%',
      right: '10%',
      bottom: '15%'
    },
    xAxis: {
      type: 'category',
      data: chartData.value.categoryData,
      boundaryGap: false,
      axisLine: { onZero: false },
      splitLine: { show: false },
      min: 'dataMin',
      max: 'dataMax'
    },
    yAxis: {
      scale: true,
      splitArea: { show: true }
    },
    dataZoom: [
      { type: 'inside', start: 50, end: 100 },
      { show: true, type: 'slider', top: '90%', start: 50, end: 100 }
    ],
    series: [
      {
        name: '日K',
        type: 'candlestick',
        data: chartData.value.values,
        itemStyle: {
          color: upColor,
          color0: downColor,
          borderColor: upBorderColor,
          borderColor0: downBorderColor
        }
      },
      {
        name: 'MA5',
        type: 'line',
        data: calculateMA(5),
        smooth: true,
        lineStyle: { opacity: 0.5 }
      },
      {
        name: 'MA10',
        type: 'line',
        data: calculateMA(10),
        smooth: true,
        lineStyle: { opacity: 0.5 }
      },
      {
        name: 'MA20',
        type: 'line',
        data: calculateMA(20),
        smooth: true,
        lineStyle: { opacity: 0.5 }
      },
      {
        name: 'MA30',
        type: 'line',
        data: calculateMA(30),
        smooth: true,
        lineStyle: { opacity: 0.5 }
      }
    ]
  };

  myChart.setOption(option);

  // Handle window resize
  window.addEventListener('resize', function () {
    myChart.resize();
  });
}

// 修改移动平均线计算函数（约第167行）
function calculateMA(dayCount: number): (number | string)[] {
  const result: (number | string)[] = [];
  const values = chartData.value.values;

  // 添加数据量校验
  if (values.length < dayCount) {
    console.warn(`数据量不足（${values.length}条），无法计算MA${dayCount}`);
    return Array(values.length).fill('-');
  }

  for (let i = 0, len = values.length; i < len; i++) {
    if (i < dayCount - 1) {
      // 修改判断条件
      result.push('-');
      continue;
    }
    let sum = 0;
    for (let j = 0; j < dayCount; j++) {
      sum += values[i - j][1]; // 确认这里使用的是收盘价索引
    }
    result.push(+(sum / dayCount).toFixed(2));
  }
  return result;
}

onMounted(async () => {
  // 获取所有股票代码
  await fetchSymbols();
  // 请求默认股票数据
  await fetchData();
});
</script>
<style scoped>
/* :deep() {
  width: 1500px;
} */
</style>
